package com.kujie.access.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kujie.access.domain.po.CustomerManagement;
import com.kujie.access.domain.query.CustomerQuery;
import com.kujie.access.domain.vo.CustomerManagementVO;
import com.kujie.access.mapper.CustomerManagementMapper;
import com.kujie.access.service.ICustomerManagementService;
import com.kujie.common.excel.utils.ExcelUtil;
import com.kujie.common.mybatis.core.page.PageQuery;
import com.kujie.system.domain.vo.SysUserVo;
import com.kujie.system.mapper.SysUserMapper;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.BatchResult;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class CustomerManagementServiceImpl implements ICustomerManagementService {
    private final CustomerManagementMapper customerManagementMapper;
    private final SysUserMapper sysUserMapper;

    @Override
    public Page<CustomerManagementVO> list(CustomerQuery customerQuery, PageQuery pageQuery) {
        // 查询用户信息
        Map<Long, String> idToNickname = sysUserMapper.selectUserIdAndNickName().stream().collect(Collectors.toMap(SysUserVo::getUserId, SysUserVo::getNickName));

        Page<CustomerManagementVO> result = pageQuery.build(new CustomerManagementVO());
        LambdaQueryWrapper<CustomerManagement> customerManagementLambdaQueryWrapper = new LambdaQueryWrapper<>();
        constructCustomerQuery(customerQuery, customerManagementLambdaQueryWrapper);

        Page<CustomerManagement> customerManagementPage = customerManagementMapper.selectPage(pageQuery.build(), customerManagementLambdaQueryWrapper);
        if (CollectionUtils.isEmpty(customerManagementPage.getRecords())) {
            log.info("数据为空");
            return result;
        }

        // 构建接口返回数据
        List<CustomerManagementVO> customerManagementVOS = customerManagementPage.getRecords().stream().map(e -> {
            CustomerManagementVO customerManagementVO = new CustomerManagementVO();
            BeanUtils.copyProperties(e, customerManagementVO);
            if (idToNickname.containsKey(e.getFollowResponsiblePerson())) {
                customerManagementVO.setFollowResponsiblePerson(idToNickname.get(e.getFollowResponsiblePerson()));
            }
            return customerManagementVO;
        }).toList();

        result.setTotal(customerManagementPage.getTotal());
        result.setRecords(customerManagementVOS);
        return result;
    }

    @Override
    public boolean insertOrUpdate(CustomerManagement customerManagement) {
        return customerManagementMapper.insertOrUpdate(customerManagement);
    }

    @Override
    public int batchDelete(List<Long> ids) {
        if (ids == null) {
            return 0;
        }

        return customerManagementMapper.deleteByIds(ids);
    }

    @Override
    public List<CustomerManagementVO> batchExport(CustomerQuery customerQuery, HttpServletResponse response) {
        // 查询用户信息
        Map<Long, String> idToNickname = sysUserMapper.selectUserIdAndNickName().stream().collect(Collectors.toMap(SysUserVo::getUserId, SysUserVo::getNickName));

        List<CustomerManagement> customerManagements;

        // 判断是否是全量导出
        if (!customerQuery.getIsAll()) {
            customerManagements = customerManagementMapper.selectByIds(customerQuery.getIds());
        } else {
            LambdaQueryWrapper<CustomerManagement> customerManagementLambdaQueryWrapper = new LambdaQueryWrapper<>();
            constructCustomerQuery(customerQuery, customerManagementLambdaQueryWrapper);
            customerManagements = customerManagementMapper.selectList(customerManagementLambdaQueryWrapper);
        }

        return customerManagements.stream().map(e -> {
            CustomerManagementVO customerManagementVO = new CustomerManagementVO();
            BeanUtils.copyProperties(e, customerManagementVO);
            if (idToNickname.containsKey(e.getFollowResponsiblePerson())) {
                customerManagementVO.setFollowResponsiblePerson(idToNickname.get(e.getFollowResponsiblePerson()));
            }
            return customerManagementVO;
        }).toList();
    }

    @Override
    public int batchImport(MultipartFile file) throws IOException {
        Map<String, Long> nicknameToId = sysUserMapper.selectUserIdAndNickName().stream().collect(Collectors.toMap(SysUserVo::getNickName, SysUserVo::getUserId));

        // 提取EXCEL的数据
        List<CustomerManagementVO> customerManagementVOS = ExcelUtil.importExcel(file.getInputStream(), CustomerManagementVO.class);
        if (CollectionUtils.isEmpty(customerManagementVOS)) {
            log.info("数据为空");
            return 0;
        }

        List<CustomerManagement> customerManagements = customerManagementVOS.stream().map(e -> {
            CustomerManagement customerManagement = new CustomerManagement();
            BeanUtils.copyProperties(e, customerManagement);
            if (nicknameToId.containsKey(e.getFollowResponsiblePerson())) {
                customerManagement.setFollowResponsiblePerson(nicknameToId.get(e.getFollowResponsiblePerson()));
            }
            return customerManagement;
        }).toList();
        List<BatchResult> batchResults = customerManagementMapper.insertOrUpdate(customerManagements);
        return batchResults.size();
    }

    @Override
    public CustomerManagementVO detail(Long id) {
        // 查询用户信息
        Map<Long, String> idToNickname = sysUserMapper.selectUserIdAndNickName().stream().collect(Collectors.toMap(SysUserVo::getUserId, SysUserVo::getNickName));

        CustomerManagement customerManagement = customerManagementMapper.selectById(id);
        CustomerManagementVO customerManagementVO = new CustomerManagementVO();
        BeanUtils.copyProperties(customerManagement, customerManagementVO);
        if (idToNickname.containsKey(customerManagement.getFollowResponsiblePerson())) {
            customerManagementVO.setFollowResponsiblePerson(idToNickname.get(customerManagement.getFollowResponsiblePerson()));
        }
        return customerManagementVO;
    }

    private void constructCustomerQuery(CustomerQuery customerQuery, LambdaQueryWrapper<CustomerManagement> customerManagementLambdaQueryWrapper) {
        customerManagementLambdaQueryWrapper.like(StringUtils.isNotEmpty(customerQuery.getCustomerName()), CustomerManagement::getCustomerName, customerQuery.getCustomerName());
        customerManagementLambdaQueryWrapper.like(StringUtils.isNotEmpty(customerQuery.getCompanyName()), CustomerManagement::getCompanyName, customerQuery.getCompanyName());
        customerManagementLambdaQueryWrapper.like(StringUtils.isNotEmpty(customerQuery.getContactDetails()), CustomerManagement::getContactDetails, customerQuery.getContactDetails());
        customerManagementLambdaQueryWrapper.eq(StringUtils.isNotEmpty(customerQuery.getFollowResult()), CustomerManagement::getFollowResult, customerQuery.getFollowResult());
        customerManagementLambdaQueryWrapper.eq(null != customerQuery.getFollowResponsiblePerson(), CustomerManagement::getFollowResponsiblePerson, customerQuery.getFollowResponsiblePerson());
    }
}
